package com.wesh.uaa.config;

import com.wesh.uaa.service.WeshClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 配置用户授权、认证方式
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter{

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private WeshClientDetailsService clientDetailsService;

    @Autowired
    private TokenStore tokenStore;

    /**
     * 配置登录用户信息服务
     * @param configurer
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
        //配置数据库获取客户信息
        configurer.withClientDetails(clientDetailsService);
        //super.configure(clients);
    }

    /**
     * 配置令牌
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager) //需要提供一个认证管理器
                .accessTokenConverter(jwtAccessTokenConverter) //jwt 进行密码转换加密
                .tokenServices(tokenServices()) //token 管理服务
                .allowedTokenEndpointRequestMethods(HttpMethod.POST)
                .authorizationCodeServices(authorizationCodeServices());
        //super.configure(endpoints);
    }

    /**
     * 配置终端（api)
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()") //token/token_key
                .checkTokenAccess("permitAll()") //check_token
                .allowFormAuthenticationForClients(); //允许表单认证提交,不放开，登录页面表单提交不了
        //super.configure(security);
    }

    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setClientDetailsService(clientDetailsService); //配置生成token获取用户信息服务
        tokenServices.setTokenStore(tokenStore); //token 存储服务
        tokenServices.setReuseRefreshToken(true);
        tokenServices.setAccessTokenValiditySeconds(7200);
        tokenServices.setReuseRefreshToken(false); // 设置为 true, 则没有 refresh_token 在返回体中
        tokenServices.setSupportRefreshToken(true); //支持 refresh token
        tokenServices.setRefreshTokenValiditySeconds(259200); //刷新令牌3天有效期
        //设置token的加密方式为 JWT
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
        tokenServices.setTokenEnhancer(tokenEnhancerChain);
        return tokenServices;
    }

    /**
     * 配置授权码存放进内存
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(){
        return new InMemoryAuthorizationCodeServices();
    }
}
